package idv.sais.ezcin;

import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;

public class KeyTouchHandler {
	private ImageButton mButton;
	private float xPushed;
	private float yPushed;
	private int mDirection;
	private int mBase;
	
	static final int DIR_NONE = 0;
	static final int DIR_UP = 1;
	static final int DIR_DOWN = 3;
	static final int DIR_LEFT = 4;
	static final int DIR_RIGHT = 2;
	
	public KeyTouchHandler(ImageButton button, int base) {
		mButton = button;
		mBase = base;
		init();
	}

	private void init() { 
		mButton.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					xPushed = event.getX();
					yPushed = event.getY();
					mButton.clearFocus();
					return true;
				case MotionEvent.ACTION_UP:
					float deltaX = event.getX() - xPushed;
					float deltaY = event.getY() - yPushed;
					
					if (Math.abs(deltaX) + Math.abs(deltaY) < 15) {
						mDirection = DIR_NONE;
					}
					else if (Math.abs(deltaX) >= Math.abs(deltaY)) {
						mDirection = deltaX > 0 ? DIR_RIGHT : DIR_LEFT;
					}
					else {
						mDirection = deltaY > 0 ? DIR_DOWN : DIR_UP;
					}
					ezcin.gCore.handleKeyClick(mBase*5 + mDirection);
					return true;
				}
				return true;
			}
		});
	}
}
